<template>
<div >
  <div id="trade-view"></div>
    <!-- <select v-model="select" >
                <option value="sz_bchusd">sz_bchusd</option>
                <option value="sz_btcusd">sz_btcusd</option>
     </select>
    <select v-model="skin" >
                <option value="white">white</option>  
                <option value="black">black</option>
     </select> -->
     <!-- <button @click="showIndicator"  style="margin-right:10px;" >指标</button>
     <button @click="fullscreen"  style="margin-right:10px;" >全屏</button> -->
     <!-- <button v-for="item in intervalBtn"  style="margin-right:10px;" 
     @click="setResolution(item.resolution,item.chartType)">
       {{item.title}}
      </button> -->
 <!-- <script type="text/javascript" src="./static/tradeview/charting_library/charting_library.min.js"></script> -->

</div>
</template>
<script>
// import { widget as TvWidget } from '../..//static/tradeview/charting_library/charting_library.min.js'
import socket from './datafeeds/socket.js'
import datafeeds from './datafeeds/datafees.js'
import {getOverrides,initLimit,disabArr} from './datafeeds/configUration.js'
import { setTimeout } from 'timers';

// import __customIndicators from './datafeeds/custom-study.js'

export default { 
  data() {
    return {
      widget: null,
      select:'sz_bchusd',
      socket:  socket,
      datafeeds: new datafeeds(this),
      symbol: null,
      interval: null,
      cacheData: {},
      lastTime: null,
      state:true,
      pricescale:10000,
      skin:'black',
      reqTimeArr:{'1':'min','1W':'week','1M':'month','30':'min30','5':'min5','60':'hours','1D':'day'},
      intervalBtn:[
                {title:'分时',resolution:'1',chartType:3},
                {title:'5分钟',resolution:'5',chartType:1},
                {title:'30分钟',resolution:'30',chartType:1},
                {title:'1小时',resolution:'60',chartType:1},
                {title:'日K',resolution:'1D',chartType:1},
                {title:'周K',resolution:'1W',chartType:1},
                {title:'月K',resolution:'1M',chartType:1},
                ],
      resolution:null,
    }
  },
  created() {
    // console.log(localStorage.getItem('pricescale'))
    // if(localStorage.getItem('pricescale')){
    //    this.pricescale=localStorage.getItem('pricescale')
    // }
    this.pricescale=this.$store.state.pricescale;
    if(this.$store.state.pricescale.num==null){
       localStorage.setItem('pricescale',100000)
    }
    this.socket.doOpen()
    this.socket.on('open', () => {

    })
    this.socket.on('message', this.onMessage);
     
  },
  
  mounted(){
          const $store=this.$store.state
          //切换周期
          $store.traViewEvent['setResolution']=this.setResolution
          //指标对话框
          $store.traViewEvent['showIndicator']=this.showIndicator
          //全屏
          $store.traViewEvent['fullscreen']=this.fullscreen
          //切换symbol
          $store.traViewEvent['upSymbol']=this.upSymbol

  },
  watch:{
     select(){
       const  _select=this.select;
       this.unSubscribe(this.interval)
       this.symbol=_select
       this.widget.chart().setSymbol(_select,()=>{
       })
        
     },
     skin(){
         this.widget.applyOverrides(getOverrides(this.skin))
     }
  },
  methods: {
    init(symbol = 'sz_bchusd', interval = 5) {
      if (!this.widget) {
        this.widget = new TradingView.widget({
          symbol: symbol,
          interval: interval,
          // fullscreen: true,
          container_id: 'trade-view',
          datafeed: this.datafeeds,
          library_path: './static/tradeview/charting_library/',
          overrides:getOverrides('black'),
          enabled_features: ['move_logo_to_main_pane','adaptive_logo'],  // 功能集    
          timezone: 'Asia/Shanghai',
          custom_css_url:`./css/tradingview_${this.skin}.css`,
          locale: 'zh',
          debug: false,
          // autosize:true,
          width:'970px',
          height:'470px',
          indicators_file_name:'./js/custom-study.js',
          disabled_features: disabArr
        })
        this.symbol = symbol
        this.interval = interval;
      }
      this.widget.onChartReady(()=>{ //Tv初始完成
          const button=this.intervalBtn
          this.widget.applyOverrides(getOverrides(this.skin))
        //   // 创建指标
        //     let option={
        //       from:1555988400,
        //       to:1555990500,
        //       includeTime:true,
        //       includeSeries:true,
        //       includedStudies:'all'
        //   }
        //  let data=this.widget.chart().exportData(option)
        //  console.log(data)
          this.createStudy(false)
          // 获取自定义指标MACD的id
          const macd=this.widget.chart().getAllStudies()[3]['id'];
          // 自定义不能更改默认高度，下面是非公开API兼容性版本不同有差异。
          this.widget.chart().getStudyById(macd)._model.m_panes[1]._stretchFactor= 604;
      })
    },
    //切换symbol
    upSymbol(symbol){ 
       this.unSubscribe(this.interval);
       this.symbol=symbol;
       this.widget.chart().setSymbol(symbol,()=>{
       })
    },
    //切换订阅周期
    setResolution(resolut,type){ 
        const _self=this.widget.chart();
              _self.setResolution(resolut);
              _self.setChartType(type);
             if(type==3){
                 this.createStudy(true)
                 const macd=this.widget.chart().getAllStudies()[0]['id'];
                 this.widget.chart().getStudyById(macd)._model.m_panes[1]._stretchFactor= 604;
             }else{
                 this.createStudy(false)
                 const macd=this.widget.chart().getAllStudies()[3]['id'];
                 this.widget.chart().getStudyById(macd)._model.m_panes[1]._stretchFactor= 604;
             }
          
    },
    // 指标对话框
    showIndicator(){  
         this.widget.chart().executeActionById("insertIndicator")
    },
    // 全屏
    fullscreen(){   
 
           let el=document.getElementById('trade-view')
           let parntHeig=el.offsetHeight;
           let parntWidth=el.offsetWidth;
           let childHeig=el.childNodes[0].offsetHeight;
           let num=0;
           let full;
              
              if(el.childNodes[0].webkitRequestFullScreen!=undefined){
                    el.childNodes[0].style=' top:0; left:0; width:100%; height:100%;'
                    el.childNodes[0].webkitRequestFullScreen()
                    window.onresize =()=>{
                     num  ? 
                     el.childNodes[0].style=`width:${970}px; height:${parntHeig}px;`:'' 
                     num =!num
                    }
              }else if(el.childNodes[0].mozRequestFullScreen!=null){
                    el.childNodes[0].style=' top:0; left:0; width:100%; height:100%;'
                    el.childNodes[0].mozRequestFullScreen()
                    window.onresize =()=>{
                     num  ? 
                     el.childNodes[0].style=`width:${970}px; height:${parntHeig}px;`:'' 
                     num =!num
                    }
              }
         
    },
    //创建指标
    createStudy(type){
      const _self=this.widget;
            _self.chart().removeAllStudies();
            //  _self.chart().createStudy('MACD', false, false,[20,2],null,{"Histogram.color":"#62a67d","MACD.color":"#EEEE00","PaneSize":"small"});
            _self.chart().createStudy("指数平滑异同移动平均线(MACD_Custom)", false, false, [14, 30, "close", 9]);
            if(type) return 
             _self.chart().createStudy('Moving Average', false, false, [5], null, {'Plot.color': 'RGBA(98, 71, 39, 1)'});
             _self.chart().createStudy('Moving Average', false, false, [10], null, {'Plot.color': 'RGBA(48, 70, 123, 1)'});
             _self.chart().createStudy('Moving Average', false, false, [20], null, {'Plot.color': 'RGBA(101, 24, 95, 1)'});
    },
     //发送请求
    send(data) { 
      if (this.socket.checkOpen()) {
        this.socket.send(data)
      } else {
        this.socket.on('open', () => {
          this.socket.send(data)
        })
      }
    },
    //中断请求，即将发起新订阅
    unSubscribe(interval) {  
        const ticker = this.symbol + "-" + interval;
        const tickertime = ticker + "load";
        const tickerstate = ticker + "state";
        const tickerCallback = ticker + "Callback";
        delete this.cacheData[ticker];
        delete this.cacheData[tickertime];
        delete this.cacheData[tickerstate];
        delete this.cacheData[tickerCallback];
        //  取消订阅
        this.send( 
              {"type":"unsubscribe"}
        )
    },
    //实时订阅
    subscribe() { 
        const _reqTimeArr=this.reqTimeArr[this.interval];  //转换给予后端的订阅周期
        this.send({"type":"subscribe","kline_time_type":_reqTimeArr,"market":this.symbol})
    },
    //数据处理
    onMessage(data) { 
       const ticker = `${this.symbol}-${this.interval}`;    //商品与周期
       const tickerCallback = ticker + "Callback";  //缓存渲染历史数据回调
       const onLoadedCallback = this.cacheData[tickerCallback];  //渲染历史回调
       const tickerstate = ticker + "state";    //缓存商品状态
       const tickerload = `${ticker}load`;    //缓存最左边请求uid时间戳
         if(data.type=='kline'){     //历史数据处理
             if(data.data.length<2 || data.data==false) {  //即代表历史数据已经没有，告诉getbar。
              //历史数据没有时，防止ws时时请求。
              this.state=false;  
              //渲染回调
              onLoadedCallback([],{noData:true})  
              return false 
            };

             let list = [];   //数据存储 
             data.data.forEach((val)=> { 
            //  遍历构造数据
               let item=JSON.parse(val)
            //  0时间 1开盘  2收盘  3最高  4最低
                  list.push({
                     time:item[0] * 1000,   //uid时间戳
                     open:Number(item[1]),
                     close:Number(item[2]),
                     high:Number(item[3]),
                     low:Number(item[4])
                  })
             })
           //  新数据即当前时间段需要的数据，直接喂给图表插件
          if(onLoadedCallback){
               onLoadedCallback(list);
               //缓存第一根bar时间，方便下次按需请求知道已请求时间段。
               this.cacheData[tickerload] = list[0].time / 1000;
               delete this.cacheData[tickerCallback];
           }
           //  告诉ws历史数据还有。
               this.state=true;
           //  缓存数据
               this.cacheData[ticker] = list; 
           //  请求当前时间订阅。
               this.subscribe()   
           //  请求完成，设置状态为false
               this.cacheData[tickerstate] = !1;
           //  缓存最后的时间   
               this.lastTime=this.cacheData[ticker][this.cacheData[ticker].length - 1 ].time;
        }
        
       //  实时数据处理
       if(data.type=='sub'){   
         let  bars= JSON.parse(data.data[0]);
       //  0时间 1开盘  2收盘  3最高  4最低
         let  barsData={time:bars[0] * 1000,open:Number(bars[1]),close:Number(bars[2]),high:Number(bars[3]),low:Number(bars[4])}
          if(this.$store.state.newPrice!=null){
            barsData.close=Number(this.$store.state.newPrice)
          }
       //  实时Bar时间大于或等于最后的bar时间时，触发updateDate通知图表更新。
         if (barsData.time >= this.lastTime && this.cacheData[ticker] && this.cacheData[ticker].length){
                this.datafeeds.barsUpdater.updateData(barsData)
                this.lastTime=barsData.time
         }
       }

    },
    getBars(symbolInfo, resolution, rangeStartDate, rangeEndDate, onLoadedCallback) {  //渲染历史数据函数
      //  商品与周期
      const ticker = `${this.symbol}-${this.interval}`;   
      //  缓存最左边请求uid时间戳
      const tickerload = `${ticker}load`;    
      //  缓存该商品状态
      const tickerstate = ticker + "state";  
     
      //  图表周期与用户选择不一致时发送当前周期请求。
      if(this.interval != resolution) {  
          this.initMessg(symbolInfo, resolution, rangeStartDate, rangeEndDate, onLoadedCallback)
          return false
      }  
     
      //  首次没有数据，发起请求，从websocket获取当前时间段的数据。
      if(!this.cacheData[ticker] && !this.cacheData[tickerstate]){  
            this.initMessg(symbolInfo, resolution, rangeStartDate, rangeEndDate, onLoadedCallback)
            this.cacheData[tickerstate] = !0;
            return false;
       }
       
      //  有数据时，并且有历史数据触发，按需加载 this.cacheData[tickerload]=历史数据的第一根时间。
      if(this.cacheData[ticker].length && this.cacheData[ticker] && this.state){
           this.initMessg(symbolInfo, resolution, rangeStartDate, this.cacheData[tickerload], onLoadedCallback)
           return false
      } 
   
    },
    initMessg(symbolInfo, resolution, rangeStartDate, rangeEndDate, onLoadedCallback){  
        //  返回请求bar数量。
        const limit = initLimit('1D', rangeStartDate, rangeEndDate);
        //  缓存商品。
        const symbol=this.symbol;
        //  索引出请求后端的时间段。
        const _resolution=this.reqTimeArr[resolution];
        //  缓存当前商品的渲染回调,在onMessage中执行。
        const tickerCallback =`${this.symbol}-${resolution}Callback`;
        //  赋值
        this.cacheData[tickerCallback]=onLoadedCallback;

        //  用户切换周期时，删除已存在商品信息。.
        if(this.interval != resolution){
            this.unSubscribe(this.interval)
            this.interval = resolution;
        }    

        //  请求历史数据。
        this.send( 
             {"type":"kline","kline_time_type":_resolution,"market":symbol,"time":rangeEndDate,"num":limit}
        )     
    },
 
  }
}
</script>

<style lang="css">


#trade-view{
    width:'970px';
    height:'465px'
}
</style>

